/**
 * Created by weirong on 2017/7/12.
 */
'use strict';

const qs = require('qs')
const fetch = require('isomorphic-fetch');

module.exports = function callApi(url, data=null, method='GET', headers={}) {
    let finUrl = url;
    let option = {
        method,
        credentials: 'include',
        headers: Object.assign({},
            {'Content-Type': 'application/json', },
            headers
        )
    }


    if(data && method != 'GET') {
        option.body = JSON.stringify(data);
    } else if(data){

        finUrl = `${url}?${qs.stringify(data)}`
    }

    return fetch(finUrl, option)
        .then(res => {
            if (res.status == 204) {
                return {res, json: {status: 204}}
            }

            return res.json().then(json => ({res, json}))
        }).then(ret => {
            const res = ret.res;
            const json = ret.json;
            const status = res.status;
            const headers = res.headers;

            if(!res.ok) {
                return Promise.reject({status, headers, message: json.message})
            }

            return {status, headers, json}
        }).catch(error => {
            return {error}
        })
}
